<?php
/*ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);*/
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

const SECRET_KEY = 'hd839Ydn98zcd4';

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}
session_start();

$usersSeeds = [
    ['user_name'=>'Илья Бетяев', 'email' => 'betyaev.ilya2004@gmail.com', 'password' => password_hash('123123', PASSWORD_DEFAULT)],
    ['user_name'=>'Тестовый акк', 'email' => 'test@test.com', 'password' => password_hash('123123', PASSWORD_DEFAULT)],
    ['avatar'=>'https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixid=M3w5MTMyMXwwfDF8c2VhcmNofDN8fHVzZXJ8ZW58MHx8fHwxNzEwOTQyNjEyfDA&ixlib=rb-4.0.3&w=1400','user_name'=>'Анна Скворцова', 'email' => 'anna@test.com', 'password' => password_hash('123123', PASSWORD_DEFAULT)],
];

$routesSeeds = [
//    ['user_id' => 3, 'routes' => '[]'],
];

$reviewsSeeds = [
    ['user_id' => 3, 'route_id' => 1, 'title'=>'Первая поездка в Волгоград',
        'rev_text'=>''
    ],
];

class Req {
    public static $data;

    public static function init() {
        self::$data = json_decode(file_get_contents('php://input'), true);
    }
}

Req::init();

class db {
    public static $db = null;
    private static $host = 'localhost';
    private static $dbname = 'u1743228_t2';
    private static $username = 'u1743228_t2';
    private static $password = 'gP5vP5tD5fuR3dQ3';

    private function __construct() {
        // Приватный конструктор, чтобы предотвратить создание экземпляров
    }

    public static function init() {
        if (self::$db === null) {
            try {
                self::$db = new PDO("mysql:host=" . self::$host . ";dbname=" . self::$dbname, self::$username, self::$password);
                self::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch (PDOException $e) {
                die("Error: " . $e->getMessage());
            }
        }
    }
}

db::init();

require_once 'auth.php';
require_once 'reviews.php';
require_once 'routes.php';

try {
    $stmt = db::$db->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([1]);
    $test_user = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    _migrates();
}

if(isset($_GET['migrates__'])) {
    _migrates();
    echo json_encode(['success' => true, 'text'=>'OK']);
    exit;
}

if (! Req::$data ) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid JSON request']);
    exit;
}

$action = '_' . (Req::$data['action'] ?? null);

if (!$action || !function_exists($action)) {
    echo json_encode(['success' => false, 'error' => 'Invalid action']);
    exit;
}

try {
    $data = call_user_func($action);
    if ( $data!==null ) {
        echo json_encode(['success' => true, 'data'=>$data]);
    } else {
        echo json_encode(['success' => false]);
    }
    die();
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    die();
}

function _migrates(){

    global $usersSeeds, $routesSeeds;

    $db = db::$db;
    migrateUsers($db);
    migrateRoutes($db);
    migrateReviews($db);

    $stmt = $db->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
    foreach ($usersSeeds as $seed) {
        $stmt->execute([$seed['email'], $seed['password']]);
    }
    $stmt = $db->prepare("INSERT INTO routes (user_id, routes) VALUES (?, ?)");
    foreach ($routesSeeds as $seed) {
        $stmt->execute([$seed['user_id'], $seed['routes']]);
    }
    $stmt = $db->prepare("INSERT INTO reviews (user_id, routes) VALUES (?, ?)");
    foreach ($routesSeeds as $seed) {
        $stmt->execute([$seed['user_id'], $seed['reviews']]);
    }
}



